package com.e3.sysmg.security.client;

import java.util.List;

import com.e3.sysmg.security.model.ModuleModel;
import com.e3.sysmg.security.model.RoleModel;
import com.e3.web.core.client.EditorListener;
import com.e3.web.core.client.GXTHelper;
import com.e3.web.core.client.GridListener;
import com.e3.web.core.client.GwtAsyncCallback;
import com.e3.web.core.client.QueryListener;
import com.e3.web.core.model.SuperQC;
import com.e3.web.widget.client.BaseAction;
import com.e3.web.widget.client.MyButton;
import com.e3.web.widget.client.MyMenuItem;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MenuEvent;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.user.client.Element;
/**
 * Role管理采用上部Grid显示Role信息，
 * 下部Grid显示所继承Role的信息。
 * 选中某一个角色可以查看该角色的所有可操作模块。
 * 双击某个角色可以编辑该角色。
 * @author Janty
 *
 */
public class RoleUI extends LayoutContainer implements GridListener<RoleModel>,QueryListener<RoleModel>,EditorListener<RoleModel>{
	
	private RoleRPCServiceAsync service = RoleRPCService.Util.getInstance();
	
	private static RoleMessages MESSAGES = RoleMessages.INSTANCE;
	
	private MyButton queryButton = new MyButton(RoleStateMachine.QUERY_ACTION);
	private MyButton newButton = new MyButton(RoleStateMachine.NEW_ACTION);
	private MyButton modifyButton = new MyButton(RoleStateMachine.MODIFY_ACTION);
	private MyButton deleteButton = new MyButton(RoleStateMachine.DELETE_ACTION);

	private ContentPanel contentPanel = new ContentPanel(new BorderLayout());
	
	private ToolBar toolbar = new ToolBar();
	
	private RoleGridPanel roleGridPanel;
	
	private RoleGridPanel parentRolesGridPanel;
	
	private RoleQueryDialog queryDialog;
	
	private RoleEditorDialog editorDialog;
	
	private ModuleDetailGridDialog moduleDetailDialog;
	
	private SelectionListener<ButtonEvent> btnSelectListener = new SelectionListener<ButtonEvent>() {
		@Override
		public void componentSelected(ButtonEvent ce) {
			MyButton item = (MyButton)ce.getSource();
			onBtnMnuEvent(item.getAction());
		}
	};
	
	private SelectionListener<MenuEvent> mnuSelectListener = new SelectionListener<MenuEvent>() {
		@Override
		public void componentSelected(MenuEvent ce) {
			ce.getSource();
			MyMenuItem item = (MyMenuItem)ce.getItem();
			onBtnMnuEvent(item.getAction());
		}
	};
	
	private Listener<MessageBoxEvent> msgBoxListener = new Listener<MessageBoxEvent>(){

		public void handleEvent(MessageBoxEvent be) {
			Button btn = be.getButtonClicked();
			onMessageBoxButton(btn);
		}
		
	};
	
	public RoleUI() {
	}

	@Override
	protected void onRender(Element parent, int index) {
		super.onRender(parent, index);
		this.setLayout(new FitLayout());
		
		BorderLayoutData bld = new BorderLayoutData(LayoutRegion.NORTH);
		bld.setSplit(true);
		bld.setMargins(new Margins(0,2,0,0));
		contentPanel.add(getRoleGridPanel(),bld);
		
		bld = new BorderLayoutData(LayoutRegion.CENTER);
		ContentPanel prolePanel = new ContentPanel(new FitLayout());
		prolePanel.add(getParentRolesGridPanel());
		prolePanel.setHeading(MESSAGES.title_parent_roles());
		contentPanel.add(prolePanel,bld);
		
		initToolBar();
		contentPanel.setTopComponent(toolbar);
		
		contentPanel.setHeaderVisible(false);
		this.add(contentPanel);
	}
	
	public SelectionListener<MenuEvent> getMenuSelectionListener(){
		return mnuSelectListener;
	}

	public RoleGridPanel getRoleGridPanel() {
		if(roleGridPanel == null ){
			roleGridPanel = new RoleGridPanel();
			roleGridPanel.addModuleGridListener(this);
			roleGridPanel.setContextMenu(RoleHelper.INSTANCE.getGridContextMenu(mnuSelectListener));
		}
		return roleGridPanel;
	}

	public RoleGridPanel getParentRolesGridPanel() {
		if(parentRolesGridPanel == null ){
			parentRolesGridPanel = new RoleGridPanel();
			parentRolesGridPanel.setContextMenu(RoleHelper.INSTANCE.getParentRoleGridContextMenu(mnuSelectListener));
		}
		return parentRolesGridPanel;
	}
	
	public RoleQueryDialog getRoleQueryDialog(){
		if(queryDialog==null){
			queryDialog = new RoleQueryDialog();
			queryDialog.addQueryListener(this);
		}
		return queryDialog;
	}
	
	public RoleEditorDialog getRoleEditorDialog(){
		if(editorDialog == null){
			editorDialog = new RoleEditorDialog();
			editorDialog.addEditorListeners(this);
		}
		return editorDialog;
	}
	
	public ModuleDetailGridDialog getModuleDetailDialog(){
		if(moduleDetailDialog==null){
			moduleDetailDialog = new ModuleDetailGridDialog();
		}
		return moduleDetailDialog;
	}
	
	private void initToolBar(){
		queryButton.addSelectionListener(btnSelectListener);
		toolbar.add(queryButton);
		newButton.addSelectionListener(btnSelectListener);
		toolbar.add(newButton);
		
		modifyButton.addSelectionListener(btnSelectListener);
		toolbar.add(modifyButton);
		deleteButton.addSelectionListener(btnSelectListener);
		toolbar.add(deleteButton);
		
	}
	
	private void onMessageBoxButton(Button btn) {
		if("yes".equals(btn.getItemId())){
			GXTHelper.maskDelete(this);
			final List<RoleModel> roleModels = getRoleGridPanel().getSelectedRoles();
			service.deleteRoles(roleModels, new GwtAsyncCallback<Void>(this) {
				@Override
				public void doSuccess(Void result) {
					getRoleGridPanel().removeDatas(roleModels);
					if(getRoleEditorDialog().isRendered()){
						getRoleEditorDialog().getRoleFormPanel().removeFromListData(roleModels);
					}
					int count = getRoleGridPanel().getRoleGridStore().getCount();
					if(count>0){
						getRoleGridPanel().setSelectValue(getRoleGridPanel().getRoleGridStore().getAt(0));
					}
				}
			});
		}
	}
	
	private void onBtnMnuEvent(BaseAction action){
		if(action == RoleStateMachine.QUERY_ACTION){
			onQuery();
		}
		else if(action == RoleStateMachine.NEW_ACTION){
			onNew();
		}
		else if(action == RoleStateMachine.MODIFY_ACTION){
			onModify();
		}
		else if(action == RoleStateMachine.DELETE_ACTION){
			onDelete();
		}
		else if(action == RoleStateMachine.SHOW_SELFMODULES_ACTION){
			onShowSelfModules();
		}
		else if(action == RoleStateMachine.SHOW_ALLMODULES_ACTION){
			onShowAllModules();
		}
	}

	private void onShowAllModules() {
		List<RoleModel> modules = getRoleGridPanel().getSelectedRoles();
		if(modules == null||modules.size()==0){
			MessageBox.alert(MESSAGES.msgbox_alert_title(), MESSAGES.msg_alert_showdetail_module(), null);
			return;
		}
		
		GXTHelper.maskQuery(this);
		service.getAllModulesOfRole(modules.get(0), new GwtAsyncCallback<List<ModuleModel>>(this) {
			@Override
			public void doSuccess(List<ModuleModel> result) {
				unmask();
				getModuleDetailDialog().showDialog(result);
			}
		});
	}

	private void onShowSelfModules() {
		List<RoleModel> modules = getRoleGridPanel().getSelectedRoles();
		if(modules == null||modules.size()==0){
			MessageBox.alert(MESSAGES.msgbox_alert_title(), MESSAGES.msg_alert_showdetail_module(), null);
			return;
		}
		
		getModuleDetailDialog().showDialog(modules.get(0).getAuthedModules());
	}

	private void onDelete() {
		List<RoleModel> modules = getRoleGridPanel().getSelectedRoles();
		String localName = MESSAGES.local_name();
		if(modules == null||modules.size()==0){
			MessageBox.alert(MESSAGES.msgbox_alert_title(), MESSAGES.msg_delete_info(localName), null);
			return;
		}
		StringBuffer msgs = new StringBuffer();
		
		for (RoleModel roleModel : modules) {
			String code = RoleHelper.INSTANCE.getFieldDisplayName(ModuleModel.CODE);
			String name = RoleHelper.INSTANCE.getFieldDisplayName(ModuleModel.NAME);
			msgs.append(code+"="+roleModel.getCode()+","+name+"="+roleModel.getName()+"\n");
		}
		MessageBox.confirm(MESSAGES.msgbox_confirm_delete_title(), MESSAGES.msg_delete_confirm(localName, msgs.toString()), msgBoxListener);
	}

	private void onModify() {
		List<RoleModel> values = getRoleGridPanel().getSelectedRoles();
		if(values==null||values.isEmpty()){
			MessageBox.alert(MESSAGES.msgbox_alert_title(),MESSAGES.msg_modify_info(MESSAGES.local_name()), null);
			return;
		}
		getRoleEditorDialog().showDialog(values.get(0), false);
	}

	private void onNew() {
		getRoleEditorDialog().showDialog(null, true);
	}

	private void onQuery() {
		getRoleQueryDialog().setVisible(true);
	}

	public void onGridSelectionChanged(RoleModel role) {
		if(role == null){
			return;
		}
		List<RoleModel> pModels = role.getParentRoles();
		getParentRolesGridPanel().setGridValues(pModels);
	}

	public void onGridRowDoubClicked(RoleModel role) {
		getRoleEditorDialog().showDialog(role, false);
	}

	public void onQuerySuccessed(SuperQC qc,List<RoleModel> results) {
		getRoleGridPanel().setGridValues(results);		
	}

	public void onEditSuccess(RoleModel model) {
		getRoleGridPanel().refreshGridData(model);
	}
	
}
